package com.lmf.mvc.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 1.开启asyncSupported = true：开启异步处理请求功能，默认是关闭
 */
@WebServlet(value = "/asyn",asyncSupported = true)
public class AsynchronousServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //解决客户端请求中文乱码
        req.setCharacterEncoding("UTF-8");
        //统一浏览器的字符集编码格式：utf-8,解决响应中文乱码
        resp.setContentType("text/html;charset=UTF-8");
        System.out.println("当前执行线程："+Thread.currentThread());
        //2.开启异步模式
        AsyncContext async = req.startAsync();
        //3.异步处理业务:有很多方法，
            // 这里调用statr()方法，启动一个线程进行业务处理，需要传入一个线程对象，且该对象实现了Runable接口
        async.start(new Runnable() {
            @Override
            public void run() {
                try {
                    sayHello();
                    async.complete();   //表示异步处理结束完成
                    //4.异步处理完成，返回客户端一个响应
                    ServletResponse response = async.getResponse();
                    response.getWriter().println("异步处理完成。。。。。。。。。。");
                    System.out.println("当前结束进程："+Thread.currentThread());
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    public void sayHello() throws InterruptedException {
        System.out.println("线程睡眠3秒..........");
        Thread.sleep(3000);
    }
}
